<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Referee;
use App\Models\CustomerInfo;
use Illuminate\Support\Facades\DB;

class StatisticalRefereePoint implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $referee;

    public function __construct(Referee $referee)
    {
        $this->referee = $referee;
    }

    public function handle()
    {
        $row = CustomerInfo::where('referee_id', $this->referee->user_id)->select(DB::raw('SUM(clue_point) as clue_point_total,SUM(driver_point) as driver_point_total,SUM(buy_car_point) as buy_car_point_total'))->first();
        $point_total = $row->clue_point_total + $row->driver_point_total + $row->buy_car_point_total;
        $this->referee->point_total = $point_total;
        $this->referee->save();
        $handler = app('App\Services\RankService')->setKey('referee-rank');
        if (!is_null($handler->zrevrank($this->referee->user_id))) {
            $handler->zrem($this->referee->user_id);
        }
        $handler->zadd($this->referee->point_total, $this->referee->user_id);
        return true;
    }
}
